#include "udpcommunicator.h"

UdpCommunicator::UdpCommunicator(QObject *parent)
    : QObject(parent), m_udpSocket(nullptr) {
}

UdpCommunicator::~UdpCommunicator() {
    stop();
}

bool UdpCommunicator::start(const QString& sendIp, int sendPort,
                            const QString& receiveIp, int receivePort) {
    stop();

    m_udpSocket = new QUdpSocket(this);
    connect(m_udpSocket, &QUdpSocket::readyRead,
            this, &UdpCommunicator::onDataReceived);

    m_sendAddress.setAddress(sendIp);
    m_receiveAddress.setAddress(receiveIp);
    m_remoteIp=receiveIp;

    return m_udpSocket->bind(m_receiveAddress, receivePort);
}

void UdpCommunicator::stop() {
    if (m_udpSocket) {
        m_udpSocket->close();
        delete m_udpSocket;
        m_udpSocket = nullptr;
    }
}

// 实现「quint16端口 + const QByteArray&数据」的重载
void UdpCommunicator::sendData(quint16 port, const QByteArray& data) {
    if (!m_udpSocket || m_remoteIp.isEmpty()) {
        qWarning() << "UDP未初始化或远程IP为空，发送失败！";
        return;
    }

    // 发送数据到指定的远程IP和端口（port是UDP目标端口）
    m_udpSocket->writeDatagram(data, QHostAddress(m_remoteIp), port);
}

void UdpCommunicator::onDataReceived() {
    while (m_udpSocket->hasPendingDatagrams()) {
        QByteArray datagram;
        datagram.resize(m_udpSocket->pendingDatagramSize());

        QHostAddress sender;
        quint16 senderPort;

        m_udpSocket->readDatagram(datagram.data(), datagram.size(),
                                  &sender, &senderPort);

        emit dataReceived(datagram, senderPort);
    }
}
